package com.kucai.yifaqapp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kucai.yifaqapp.R;
import com.kucai.yifaqapp.global.HttpAdress;
import com.kucai.yifaqapp.global.Info;
import com.kucai.yifaqapp.model.CustomObserver;
import com.kucai.yifaqapp.model.network.HttpJsonUtils;
import com.kucai.yifaqapp.model.network.entity.res.ResBanner;
import com.kucai.yifaqapp.model.network.entity.res.ResLogin;
import com.kucai.yifaqapp.model.network.entity.res.urlListBean;
import com.kucai.yifaqapp.ui.view.SplushView;
import com.kucai.yifaqapp.util.EventBus.refreshFragmentEvent;
import com.kucai.yifaqapp.util.Md5;
import com.kucai.yifaqapp.util.SYSOUtils;
import com.kucai.yifaqapp.util.SpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2017/8/4.
 * 启动页面
 */

public class SplashActivity extends Activity implements SplushView, EasyPermissions.PermissionCallbacks {
    private boolean isAddressuse = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        //首先获取到我们的域名组
        getUrlList();
    }

    List<String> urllist = new ArrayList<>();

    private void getUrlList() {
        HttpJsonUtils.getHttpApiInstance()
                .getUrlList("https://app.e80002.com/apps/url.json")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<urlListBean>() {
                    @Override
                    protected void onCustomNext(urlListBean resLogin) {
//                        urllist.add(resLogin.getUrlone());
//                        urllist.add(resLogin.getUrltwo());
//                        urllist.add(resLogin.getUrlthree());
//                        SYSOUtils.sOut_("链接地址"+resLogin.getUrlone());
                        urllist.add("https://demo.wuxianplay.com/");
                        beginPing();
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        goHome();
                    }
                });
    }

    public void beginPing() {
        //当进入界面之前  我们首先开始ping可用的服务器
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < urllist.size(); i++) {
                    if (ping(urllist.get(i), 2000)) {
                        //直接将我们的baseurl替换掉
                        Log.e("xdh", "选择域名");
                        HttpAdress.adress = urllist.get(i);
                        isAddressuse = true;
                        if (isAddressuse) {
                            String user = SpUtils.getString(SplashActivity.this, "User");
                            if (!TextUtils.isEmpty(user) && new Gson().fromJson(user, ResLogin.DataBean.class) != null) {
                                //这里开始重新登录
                                String issavepass = SpUtils.getString(SplashActivity.this, "loginpass");
                                if (!issavepass.isEmpty()) {
                                    if (issavepass.equals("1")) {
                                        //开始自动登录
                                        login();
                                    } else {
                                        //直接进入主界面
                                        goHome();
                                    }
                                } else {
                                    goHome();
                                }
                            } else {
                                goHome();
                            }
                        } else {

                        }
                        return;
                    }
                }
            }
        }).start();
    }

    private void goHome() {
        /**
         * Request permissions.
         */
        String[] ids = {Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        requestPermission(this, "请同意以下权限以确保版本更新功能能够使用", 200, ids);
    }

    /**
     * 请求权限
     *
     * @param context
     */
    public static void requestPermission(Activity context, String tip, int requestCode, String[] perms) {
        EasyPermissions.requestPermissions(context, tip, requestCode, perms);
    }

    private void login() {
        String username = SpUtils.getString(this, "username");
        String password = SpUtils.getString(this, "password");
        HttpJsonUtils.getHttpApiInstance()
                .login(HttpAdress.getuseAdress() + "api/m/login", username, Md5.toMd5(password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResLogin>() {
                    @Override
                    public void onNext(ResLogin resLogin) {
                        try {
                            if (resLogin.code == 0 && resLogin.data != null) {
                                Info.user = resLogin.data;
                                SpUtils.clearUser(SplashActivity.this);
                                SpUtils.putString(SplashActivity.this, "User", new Gson().toJson(resLogin.data));
                                //这里通知更新数据
                                EventBus.getDefault().post(new refreshFragmentEvent("refresh"));
                                goHome();
                            } else {
                                goHome();
                            }
                        } catch (Exception e) {
                            goHome();
                        }
                    }

                    @Override
                    protected void onCustomNext(ResLogin resLogin) {

                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        goHome();
                    }
                });
    }

    private void enterHomeActivty() {
        if (isAddressuse) {
            Intent intent = new Intent(this, LauncherActivity.class);
            startActivity(intent);
            finish();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions 权限处理请求结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //开始跳转主界面
        enterHomeActivty();
    }

    //拒绝授权
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this, "您拒绝了权限，将无法版本更新，如果需要版本更新功能，请到设置界面打开相应权限", Toast.LENGTH_LONG).show();
        enterHomeActivty();
    }

    public boolean ping(String urlString, int timeOutMillSeconds) {
        URL url;
        try {
            url = new URL(urlString);
            URLConnection co = url.openConnection();
            co.setConnectTimeout(timeOutMillSeconds);
            co.connect();
            Log.e("xdh", "域名可用" + urlString);
            return true;
        } catch (Exception e1) {
            url = null;
            Log.e("xdh", "域名不可用" + urlString);
            return false;
        }
    }
}
